package com.yboot.starter.shiro.core.advise;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import com.yboot.starter.common.core.web.vo.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 功能描述
 *
 * @author yangcs
 * @date 2025/8/20
 */
@Order(70)
@RestControllerAdvice
public class ShiroExceptionHandler {

    private static final Map<Class<? extends Exception>, String> EXCEPTION_MESSAGES = MapUtil.of(
            new Pair<>(UnknownAccountException.class, "用户名不存在"),
            new Pair<>(IncorrectCredentialsException.class, "密码错误"),
            new Pair<>(LockedAccountException.class, "账户被锁定"),
            new Pair<>(DisabledAccountException.class, "账户被禁用"),
            new Pair<>(ExcessiveAttemptsException.class, "尝试次数过多"),
            new Pair<>(ExpiredCredentialsException.class, "凭证过期"),
            new Pair<>(UnauthorizedException.class, "权限不足")
    );

    @ExceptionHandler(value = ShiroException.class)
    @ResponseBody
    public Result handleException(Exception e) {
        // 处理异常，例如记录日志等
        return Result.error(EXCEPTION_MESSAGES.getOrDefault(e.getClass(), e.getMessage()));
    }
}
